package com.tsmti.core.util;

import com.tsmti.core.common.entity.BaseTreeNode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package：com.tsmti.core.util
 * @Class：TreeSortUtils
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/3/24 12:35
 * @Company:
 * @Version：
 * @Modified By:
 */
public class TreeSortUtils<ID extends Serializable> implements Serializable {

    private static final long serialVersionUID = 2444638065060902858L;

    private List<BaseTreeNode<ID>> baseTreeNodes;

    private List<BaseTreeNode<ID>> newBaseTreeNodes;

    public static <T extends Serializable> TreeSortUtils<T> create() {
        TreeSortUtils<T> treeSortUtil = new TreeSortUtils<T>();
        return treeSortUtil;
    }

    public TreeSortUtils() {
        this.newBaseTreeNodes = new ArrayList<BaseTreeNode<ID>>();
    }

    /**
     * 获得根节点
     *
     * @param
     */
    public List<BaseTreeNode<ID>> getTopNodes() {
        List<BaseTreeNode<ID>> list = new ArrayList<BaseTreeNode<ID>>();
        for (BaseTreeNode<ID> treeable : baseTreeNodes) {
            if (treeable.isRoot()) {
                list.add(treeable);
            }
        }
        return list;
    }

    /**
     * 解析根节点
     *
     * @param node
     */
    public void parseSubNode(BaseTreeNode<ID> node) {
        for (BaseTreeNode<ID> treeable : baseTreeNodes) {
            if (!ObjectUtils.isNullOrEmpty(treeable.getParentId()) && treeable.getParentId().equals(node.getId())) {
                newBaseTreeNodes.add(treeable);
                parseSubNode(treeable);
            }
        }
    }

    /**
     * 运行排序
     */
    @SuppressWarnings("unchecked")
    public TreeSortUtils<ID> sort(List<?> treeNodes) {
        this.baseTreeNodes = (List<BaseTreeNode<ID>>) treeNodes;
        List<BaseTreeNode<ID>> rootNodes = getTopNodes();
        for (BaseTreeNode<ID> rootNode : rootNodes) {
            newBaseTreeNodes.add(rootNode);
            parseSubNode(rootNode);
        }
        this.baseTreeNodes.clear();
        this.baseTreeNodes.addAll(newBaseTreeNodes);
        return this;
    }

    /**
     * 运行排序
     */
    @SuppressWarnings("unchecked")
    public TreeSortUtils<ID> async(List<?> treeNodes) {
        this.baseTreeNodes = (List<BaseTreeNode<ID>>) treeNodes;
        for (BaseTreeNode<ID> treeNode : this.baseTreeNodes) {
            treeNode.setLoaded(true);
        }
        return this;
    }

    @SuppressWarnings("unchecked")
    public TreeSortUtils<ID> sync(List<?> treeNodes) {
        this.baseTreeNodes = (List<BaseTreeNode<ID>>) treeNodes;
        for (BaseTreeNode<ID> treeNode : this.baseTreeNodes) {
            treeNode.setLoaded(false);
        }
        return this;
    }

}
